package com.lottery.im.module.result.ui;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.LongDragonInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.module.result.adapter.LongDragonAdapter;
import com.lottery.im.module.result.presenter.LongDragonPresenter;
import com.lottery.im.module.result.ui.game.Game28Fragment;
import com.lottery.im.module.result.ui.game.GameFastFragment;
import com.lottery.im.module.result.ui.game.GameLotteryFragment;
import com.lottery.im.module.result.ui.game.GamePkFragment;
import com.lottery.im.module.result.view.LongDragonView;
import com.lottery.im.util.Utils;
import com.lottery.im.widget.dialog.LongDragonSelectDialog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 所有彩种长龙统计
 */
public class LongDragonFragment extends BaseSwipeFragment<LongDragonPresenter>
    implements LongDragonView {

  private String[] mTabNames = { "连续开出", "连续未开" };
  private String[] ballNameArr =
      { "第1球", "第2球", "第3球", "第4球", "第5球", "第6球", "第7球", "第8球", "第9球", "第10球" };
  private String[] ballTypeArr =
      { "大", "小", "单", "双", "龙", "虎", "和" };
  @BindView(R.id.long_dragon_list) RecyclerView mRecyclerView;

  private List<LongDragonInfo> mAllList = new ArrayList<>();
  private List<LongDragonInfo> mLongList = new ArrayList<>();
  private ArrayList<String> mGameTypeList = new ArrayList<>();
  private LongDragonAdapter mAdapter;
  private View mHeaderView;
  private CommonTabLayout mTabLayout;
  private int curIndex = 2;
  private String type = "2";
  private TextView mTvTitle;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_dragon_long;
  }

  @Override protected void initPresenter() {
    presenter = new LongDragonPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mAdapter = new LongDragonAdapter(mLongList);
    mRecyclerView.setAdapter(mAdapter);
    mAdapter.addHeaderView(getHeaderView());
    mAdapter.setOnItemCheckClickListener(position -> {
      String gameType = mLongList.get(position).getGameType();
      String gameName = mLongList.get(position).getGameName();
      if (Constants.lotteryArr.contains(gameType) || Constants.sd115Arr.contains(gameType)) {
        startFragment(GameLotteryFragment.create(gameType, gameName));
      } else if (Constants.pkArr.contains(gameType)) {
        startFragment(GamePkFragment.create(gameType, gameName));
      } else if (Constants.fastArr.contains(gameType)) {
        startFragment(GameFastFragment.create(gameType, gameName));
      } else if (Constants.bj28Arr.contains(gameType)) {
        startFragment(Game28Fragment.create(gameType, gameName));
      }
    });
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size_dp1))
        .hideLastDivider()
        .build()
        .addTo(mRecyclerView);
    presenter.queryAllStatistics();
  }

  /*
   * 头部 条件筛选
   * */
  private View getHeaderView() {
    if (null == mHeaderView) {
      mHeaderView = getLayoutInflater().inflate(R.layout.header_long_dragon_list, null);
      mTabLayout = mHeaderView.findViewById(R.id.tabLayout);
      mTvTitle = mHeaderView.findViewById(R.id.head_title_name);
      TextView mTvGameNum = mHeaderView.findViewById(R.id.tv_game_num);
      initTabs();
      mHeaderView.findViewById(R.id.layout_select)
          .setOnClickListener(v -> new LongDragonSelectDialog().create(getActivity(), v1 -> {
            mTvGameNum.setText(curIndex + "");
            selectLongList();
            LongDragonSelectDialog.dismiss();
          }, position -> curIndex = position + 2).show());
    }
    return mHeaderView;
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return mTabNames[position];
        }

        @Override public int getTabSelectedIcon() {
          return 0;
        }

        @Override public int getTabUnselectedIcon() {
          return 0;
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    selectTab(0);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        selectTab(position);
      }

      @Override public void onTabReselect(int position) {
        selectTab(position);
      }
    });
  }

  public void selectTab(int position) {
    for (int i = 0; i < mTabNames.length; i++) {
      if (i == position) {
        TextView tv = mTabLayout.getTitleView(i);
        tv.setHeight((int) getResources().getDimension(R.dimen.space6));
        tv.setWidth((int) getResources().getDimension(R.dimen.dimen75));
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(R.drawable.bg_tab_item_result);
      } else {
        TextView tv = mTabLayout.getTitleView(i);
        tv.setHeight((int) getResources().getDimension(R.dimen.space6));
        tv.setWidth((int) getResources().getDimension(R.dimen.dimen75));
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(0);
      }
    }
    switch (position) {
      case 0:
        type = "2";
        mTvTitle.setText("连开期数");
        selectLongList();
        break;
      case 1:
        type = "3";
        mTvTitle.setText("连续未开期数");
        selectLongList();
        break;
    }
  }

  @OnClick({ R.id.iv_back, R.id.iv_select })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.iv_select:
        startFragmentForResult(new AllGameSelectFragment(), Constants.REQUEST_CODE_SELECT);
        break;
    }
  }

  @Override protected void onFragmentResult(int requestCode, int resultCode, Intent data) {
    super.onFragmentResult(requestCode, resultCode, data);
    if (data != null && requestCode == Constants.REQUEST_CODE_SELECT && resultCode == RESULT_OK) {
      mGameTypeList = data.getStringArrayListExtra("gameTypeList");
      selectLongList();
    }
  }

  private void selectLongList() {
    mLongList.clear();
    for (int i = 0; i < mAllList.size(); i++) {
      if (type.equals(mAllList.get(i).getType())
          && mAllList.get(i).getGameNum() >= curIndex) {
        if (mGameTypeList == null || mGameTypeList.size() == 0) {
          mLongList.add(mAllList.get(i));
        } else {
          for (int j = 0; j < mGameTypeList.size(); j++) {
            if (mAllList.get(i).getGameType().equals(mGameTypeList.get(j))) {
              mLongList.add(mAllList.get(i));
            }
          }
        }
      }
    }
    mAdapter.notifyDataSetChanged();
  }

  @Override public void querySuccess(List<List<String>> list) {
    for (int i = 0; i < list.size(); i++) {
      for (int j = 0; j < list.get(i).size(); j++) {
        String string = list.get(i).get(j);
        if (j > 5) {
          String type = list.get(i).get(0);
          String gameType = list.get(i).get(1);
          String gameName = list.get(i).get(2);
          if (!TextUtils.isEmpty(string)) {
            String[] str = string.split(",");
            if (str.length > 0) {
              for (int k = 0; k < str.length; k++) {
                if (Utils.isInteger(str[k])) {
                  int a = Integer.parseInt(str[k]);
                  if (a > 1) {
                    if (Constants.fastArr.contains(gameType)) {
                      LongDragonInfo info =
                          new LongDragonInfo(type, gameType, gameName, "总和", ballTypeArr[k], a);
                      mAllList.add(info);
                    } else if (Constants.bj28Arr.contains(gameType)) {

                    } else {
                      LongDragonInfo info =
                          new LongDragonInfo(type, gameType, gameName, ballNameArr[j - 6],
                              ballTypeArr[k],
                              a);
                      mAllList.add(info);
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    Collections.sort(mAllList, new SortByNum());
    mLongList.clear();
    for (int i = 0; i < mAllList.size(); i++) {
      if ("2".equals(mAllList.get(i).getType())) {
        mLongList.add(mAllList.get(i));
      }
    }
    mAdapter.notifyDataSetChanged();
  }

  class SortByNum implements Comparator {//按期数从大到小排序

    public int compare(Object o1, Object o2) {
      LongDragonInfo s1 = (LongDragonInfo) o1;
      LongDragonInfo s2 = (LongDragonInfo) o2;
      if (s1.getGameNum() < s2.getGameNum()) {
        return 1;
      } else if (s1.getGameNum() == s2.getGameNum()) {
        return 0;
      } else {
        return -1;
      }
    }
  }
}
